import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-06-16
 * Time: 22:05
 */
public class TcpEchoCilent {

    private Socket socket = null;

    public TcpEchoCilent(String serverIp, int serverPort) throws IOException {
        //直接设置服务器地址和端口
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(System.in);
            //为了使用方便，套壳操作
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true) {
                //1.从控制台读取请求输入
                String request = scanner.next();
                //2.发送请求到服务器
                printWriter.println(request);
                //刷新缓冲区才是真正的发送数据
                printWriter.flush();
                //3.读取服务器返回的响应
                String response = scannerNet.next();
                //4。打印到控制台
                System.out.println(response);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoCilent cilent = new TcpEchoCilent("127.0.0.1", 9090);
        cilent.start();
    }

}
